package net

import (
	"fmt"
	"io"
	"lite-json-golang/parser"
	"net/http"
	"strconv"
	"strings"
	"time"
)

type JsonServer struct {
}

func (s *JsonServer) ServeHTTP(res http.ResponseWriter, req *http.Request) {
	url := req.RequestURI
	fmt.Println("url", url)
	if strings.HasPrefix(url, "/pretty") {
		s.pretty(res, req)
	} else {
		s.homePage(res, req)
	}
}

func (s *JsonServer) pretty(res http.ResponseWriter, req *http.Request) {
	str := req.FormValue("json")
	if len(str) == 0 {
		s.writeString(res, "需要传入JSON字符串")
		return
	}
	fmt.Println("json", str)
	lexer := parser.NewLexer(str)
	pretty := lexer.Parse()
	s.writeString(res, pretty)
}

func (s *JsonServer) homePage(res http.ResponseWriter, req *http.Request) {
	s.writeString(res, defaultPage)
}

func (s *JsonServer) writeString(res http.ResponseWriter, message string) {
	_, err := io.WriteString(res, message)
	if err != nil {
		fmt.Println(err)
	}
}

func (s *JsonServer) Start(port int) {
	//http.Handle("/pretty", s)
	addr := ":" + strconv.Itoa(port)
	fmt.Println("addr:", addr)
	serv := &http.Server{
		Addr:           addr,
		Handler:        s,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	err := serv.ListenAndServe()
	if err != nil {
		fmt.Println(err)
	}
}

const defaultPage = `<html>

<head>
    <style>
        .main {
            display: inline-flex;
        }

        .leftText {
            width: 400;
            height: 400;
            word-break: break-all;
            flex-wrap: wrap;
            align-content: normal;
        }

        .rightText {
            width: 800;
            height: 400;
            word-break: break-all;
            flex-wrap: wrap;
        }

        .leftDiv {
            margin-left: 100;
        }

        .btnDiv {
            margin-left: 100;
            margin-top: 50;
        }

        .btn {
            width: 100;
            height: 40;
        }
    </style>

    <script>
        // Example POST method implementation:
        async function postData(url = '', data = '') {
            // Default options are marked with *
            const response = await fetch(url, {
                method: 'POST', // *GET, POST, PUT, DELETE, etc.
                mode: 'cors', // no-cors, *cors, same-origin
                cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
                credentials: 'same-origin', // include, *same-origin, omit
                headers: {
                    // 'Content-Type': 'application/json'
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                redirect: 'follow', // manual, *follow, error
                referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
                body: data // body data type must match "Content-Type" header
            });
            return response.text(); // parses JSON response into native JavaScript objects
        }

        function pretty() {
            let json = document.getElementById('leftText').value;
            let params = 'json=' + encodeURIComponent(json)
            postData('/pretty', params)
                .then(data => {
                    console.log(data); // JSON data parsed by data.json() call
                    document.getElementById('rightText').value = data
                });
        }
    </script>
</head>

<body>
    <div class="main">
        <div class="leftDiv">
            <h1>源字符串：</h1>
            <textarea name="json" class="leftText" id="leftText" ></textarea>
        </div>

        <div class="leftDiv">
            <h1>格式化字符串：</h1>
            <textarea class="rightText" id="rightText" ></textarea>
        </div>
    </div>
    <br>
    <div class="btnDiv">
        <button onclick="pretty()" class="btn" title="格式化">格式化</button>
    </div>
</body>

</html>`
